package org.qiyu.live.api.websockerDemo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: Nio 网络请求
 * @Description: TODO
 * @Author zhangguangyan
 * @Date 2023/09/02/ 11:36:45
 * @Version 1.0
 */
public class NioSimpleServer {
    private static List<SocketChannel> acceptSockertList =  new ArrayList<>();

    public static void main(String[] args) throws Exception{
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9090));
        //设置非阻塞
        serverSocketChannel.configureBlocking(false);
        //异步
        new Thread(()->{
            while (true){
                for (SocketChannel socketChannel : acceptSockertList) {
                    try {
                        //获取数据的输入流
                        ByteBuffer allocate = ByteBuffer.allocate(10);
                        //在nio中,read是非阻塞的状态
                        socketChannel.read(allocate);
                        System.out.println("服务器接收到的数据:"+new String(allocate.array()));
                    } catch (IOException e) {
                       throw new RuntimeException(e);
                    }
                }
                try{
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    throw new RuntimeException(e);
                }
            }
        }).start();
        while (true){
            //在nio立马的accept函数是非阻塞的函数
            SocketChannel accept = serverSocketChannel.accept();
            if(accept!=null){
                System.out.println("有新的连接进来了");
                acceptSockertList.add(accept);
            }
        }
    }
}
